package com.example.mynote.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mynote.R;
import com.example.mynote.base.BaseActivity;
import com.example.mynote.entity.StickyNote;

import org.litepal.LitePal;

public class EditActivity extends BaseActivity {

    private android.widget.ImageButton editBack;
    private android.widget.TextView editText;
    private android.widget.ImageButton editSave;
    private android.widget.EditText editNote;
    private android.widget.TextView editNum;

    @Override
    protected int initLayout() {
        return R.layout.activity_edit;
    }

    @Override
    protected void initView() {

        editBack = (ImageButton) findViewById(R.id.edit_back);
        editText = (TextView) findViewById(R.id.edit_text);
        editSave = (ImageButton) findViewById(R.id.edit_save);
        editNote = (EditText) findViewById(R.id.edit_note);
        editNum = (TextView) findViewById(R.id.edit_num);
    }

    @Override
    protected void initData() {

        editBack.setOnClickListener(v -> onBackPressed());
        editText.setText("编辑");

        String content = getIntent().getStringExtra("content");
        editNote.setText(content);

        editSave.setOnClickListener(v -> {
            ContentValues values = new ContentValues();
            values.put("content", editNote.getText().toString());
            LitePal.updateAll(StickyNote.class, values, "content = ?", content);
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
            finish();
        });

        editNote.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                editNum.setText(s.length() + "字");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
}